package com.hou.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: hbx
 * @create: 2024-07-30
 **/
@RestController
@RequestMapping("/api")
public class ThreadLocalController {

    private ThreadLocal<Integer> currentUser = ThreadLocal.withInitial(() -> null);

    @GetMapping("/wrong")
    public Map helloword(@RequestParam("userId") Integer userId) {
        Map map = new HashMap();
        //设置用户信息之前先查一下ThreadLocal中的用户信息
        String before = Thread.currentThread().getName() + ":" + currentUser.get();

        try {
            currentUser.set(userId);
            //设置用户信息之后在查一下ThreadLocal中的用户信息
            String after = Thread.currentThread().getName() + ":" + currentUser.get();
            //汇总两次查询结果
            map.put("before",before);
            map.put("after",after);

            return map;
        }finally {
            currentUser.remove();
        }
    }
}
